package com.holdtime.jtt809dataservice.server.runnable;

import com.holdtime.jtt809dataservice.common.NettyCommon;
import com.holdtime.jtt809dataservice.common.domain.ChannelHandlerContextManager;
import com.holdtime.jtt809dataservice.common.event.MessageReceiveEvent;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import protocol.jtt809.JTT809Packet;
import protocol.jtt809.JTT809Util;
import protocol.jtt809.body.RawBody;

/**
 * author: sunwei
 * Date: 2025/3/14 18:31
 * Description:
 */
@Slf4j
public class DealSubordinatePlatformMessageReceive implements Runnable {
    private ChannelHandlerContext channelHandlerContext;

    private Object message;

    private ApplicationContext context;

    public DealSubordinatePlatformMessageReceive(
            ChannelHandlerContext channelHandlerContext, Object message, ApplicationContext context) {
        this.channelHandlerContext = channelHandlerContext;
        this.message = message;
        this.context = context;
    }

    @Override
    public void run() {
        if (message instanceof JTT809Packet) {
            JTT809Packet<RawBody> packet = (JTT809Packet<RawBody>) message;

            //验证校验码
            if (packet.checkCrcCode()) {
                log.info("收到809数据:{}", JTT809Util.antisense(packet.array()));
                Attribute<String> attr = channelHandlerContext.channel()
                        .attr(NettyCommon.numberKey);
                String number = attr.get();
                if (number == null) {
                    number = String.valueOf(packet.getMsgGnsscenterid());
                    attr.set(number);
                    log.debug("JTT809-server连接" + channelHandlerContext.channel().remoteAddress().toString()
                            + "=>" + number);
                }
                ChannelHandlerContextManager.getCurrent().put(number, channelHandlerContext);
                context.publishEvent(new MessageReceiveEvent(packet, channelHandlerContext));
            }
        }
    }
}
